#!/usr/bin/python
# coding:utf-8

import redis
from agent.agent import Agent
from datetime import datetime
import time
import string
import platform


class RedisAgent(Agent):
    """docstring for ClassName"""

    pool = None

    def __init__(self, host, port, **kw):
        super(RedisAgent, self).__init__(host, port)
        if "app" in kw:
            self.app = kw["app"]
        else:
            self.app = "TestDlg"
        if "outputpath" in kw:
            self.outputpath = kw["outputpath"]
        else:
            self.outputpath = "./"
        RedisAgent.pool = redis.ConnectionPool(
            host=self.host, port=self.port, decode_responses=True
        )
        self._engin = None

    def Init(self):
        if self._engin == None:
            self._engin = redis.Redis(connection_pool=RedisAgent.pool)

    def LogRun(self):
        osName = platform.system()
        while True:
            try:
                t = self._engin.brpop(self.app, timeout=1000)
                if t == None:
                    continue
                if len(t) != 2:
                    continue
                pre = t[0]
                str = t[1]
                index = str.index("=")
                if index < 0:
                    continue
                app = str[0:index]
                data = str[index:]
                timef = time.strftime("%Y-%m-%d", time.localtime())
                file = self.outputpath + pre + "-" + app + "-" + timef
                if osName == "Windows":
                    print("file=", file, "write data", data)
                else:
                    fo = open(file, "a")
                    fo.write(data)
                    fo.close()
            except Exception as e:
                print("err", e)
                time.sleep(1)
